package com.ds.common.route.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class RuntimeContextInterceptor implements HandlerInterceptor {

    ContextHandler contextHandler;

    @Autowired
    public RuntimeContextInterceptor(ContextHandler contextHandler) {
        this.contextHandler = contextHandler;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        RuntimeContextHolder.setContext(contextHandler.getContext(request.getServerName()));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        // 可以在这里添加处理逻辑
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理上下文
        RuntimeContextHolder.clearContext();
    }
}
